<?php

namespace app\api\controller\worker;

use app\api\controller\Base;
use app\common\model\AdminModel;
use app\common\model\node\NodeModel;
use app\common\model\node\NodeProcessModel;
use app\common\model\offer\GoodsModel;
use app\common\model\RoleAuthModel;
use app\common\model\RoleAuthShowModel;
use app\common\model\RoleModel;
use app\common\model\worker\CustomerActionLogModel;
use app\common\model\worker\CustomerAuthModel;
use app\common\model\worker\CustomerBudgetModel;
use app\common\model\worker\CustomerFollowLogModel;
use app\common\model\worker\CustomerGoodsDataModel;
use app\common\model\worker\CustomerGoodsDesertModel;
use app\common\model\worker\CustomerModel;
use app\common\model\worker\CustomerRulerDetailModel;
use app\common\model\worker\CustomerRulerModel;
use app\common\model\worker\OfferModel;
use app\common\model\worker\CustomerDesertModel;
use app\common\model\worker\TaskModel;
use DateTime;
use think\facade\Db;
use app\common\model\worker\RecommendModel;
use think\Request;

class CustomerController extends Base
{

    private $model;
    private $taskModel;
    /**
     * 构造方法
     * @access public
     * @throws \Exception
     */
    public function __construct()
    {

        parent::__construct();
        $this->checkLogin();
        $this->model = new CustomerModel();
        $this->taskModel = new TaskModel();

    }



    /**
     * 添加客户
     */
    public function add()
    {
        $data = $this->request->param();
        $rule = [
            'business_name|商机名称'=>'require',
            'name|客户姓名'=>'require',
            'mobile|手机号码'=>'require|mobile',
            'province|省'=> 'require',
            'city|市'=> 'require',
            'dist|区'=> 'require',
            'house_estate|小区' => 'require',
            'address|楼牌号码详细地址'=>'require',
            'channel_id|客来渠道|'=>'require|number',
            'is_in_store|是否进店'=>'require|number',
            'customer_area|建筑面积'=>'require',
            'customer_basics|装修基础工程造价'=>'require',
            'house_attr|房屋性质'=>'require|number',
            'room_nums|房屋户型 几室'=>'require|number',
            'who_nums|房屋户型 几卫'=>'require|number',
            'hall_nums|房屋户刑 几厅'=>'require|number',
            'expect_status|回款周期'=>'require|number',
            'progress_status|家装进度'=>'require|number',
            'customer_pain_content|客户痛点'=>'require',
            'structure_status|房屋结构'=>'require',
            'customer_type|装修风格'=>'require|number',
            'customer_goods_names|选择产品'=>'require',

        ];
        //房屋结构 为商业 不需要判断几室几厅
        if($data['structure_status'] == 4){
            unset($rule['room_nums'],$rule['who_nums'],$rule['hall_nums']);
        }
        $this->validate($data,$rule);
        $info = $this->model->where('mobile',$data['mobile'])->find();
        if(!empty($info)) //exception('客户信息已经存在');
        {
            $this->result([],'客户信息已经存在',0);
        }
        if(!empty($data['customer_imgs'])){
            $data['customer_imgs'] = json_encode($data['customer_imgs'],JSON_UNESCAPED_UNICODE);
        }
        if(!empty($data['customer_file'])){
            $data['customer_file'] = json_encode($data['customer_file'],JSON_UNESCAPED_UNICODE);
        }
        // 启动事务
        Db::startTrans();
        $data['action_admin_id'] = $this->loginInfo['id'];
        $result = $this->model->add($data,$this->loginInfo['id']);
        $data['customer_id'] = $result['id'];//客户id
        if(!$result){
            // 回滚事务
            Db::rollback();
            $this->result([], "操作失败", 0);
        }
        $actionLog = [
            'customer_id'=>$result['id'],
            'action_log'=>json_encode($result),//创建者
            'remark'=>'add',
            'action_admin_id'=>$this->loginInfo['id'],//操作人di
        ];

        $result = CustomerActionLogModel::create($actionLog);
        if(!$result){
            // 回滚事务
            Db::rollback();
            $this->result([], "操作失败", 0);
        }

        $result = $this->model->addCustomerGoodsData($data,$this->loginInfo['id']);
        if(!$result){
            // 回滚事务
            Db::rollback();
            $this->result([], "操作失败", 0);
        }
        Db::commit();
        $this->result($result);

    }

    /**
     * 编辑客户
     */
    public function edit()
    {
        $roles_ids = $this->role_ids;
        if(!in_array(7,$roles_ids)){
            exception('该用户没有权限，只有业务员有操作权限！');
        }
        $data = $this->request->param();
        $rule =[
            'business_name|商机名称'=>'require',
            'name|客户姓名'=>'require',
            'mobile|手机号码'=>'require|mobile',
            'house_estate|小区' => 'require',
            'address|楼牌号码详细地址'=>'require',
            'channel_id|客来渠道'=>'require',
            'is_in_store|是否进店'=>'require',
            'customer_area|建筑面积'=>'require',
            'customer_basics|装修基础工程造价'=>'require',
            'house_attr|房屋性质'=>'require',
            'room_nums|房屋户型 几室'=>'require',
            'who_nums|房屋户刑 几卫'=>'require',
            'hall_nums|房屋户刑 几厅'=>'require',
            //'expect_status|回款周期'=>'require',
           // 'progress_status|家装进度'=>'require',
            'customer_pain_content|客户痛点'=>'require',
            'structure_status|房屋结构'=>'require',
            'customer_type|装修风格'=>'require',
            // 'customer_goods_names|选择产品'=>'require',

        ];
        //房屋结构 为商业 不需要判断几室几厅
        if($data['structure_status'] == 4){
            unset($rule['room_nums'],$rule['who_nums'],$rule['hall_nums']);
        }
        $this->validate($data,$rule);
        $info = $this->model->where('mobile',$data['mobile'])->find();
        if ($info['mobile'] != $data['mobile']) {
            $info = $this->where('mobile', $data['mobile'])
                ->where('id', $data['id'])
                ->find();
            if ($info) //exception( '该客户已存在');
            {
                $this->result([],'该客户已存在',0);
            }
        }
        //todo 验证是否有编辑权限
//        if(!empty($data['customer_imgs'])){
//            $data['customer_imgs'] = json_encode($data['customer_imgs'],JSON_UNESCAPED_UNICODE);
//        }
//        if(!empty($data['customer_file'])){
//            $data['customer_file'] = json_encode($data['customer_file'],JSON_UNESCAPED_UNICODE);
//        }

        // 启动事务
        Db::startTrans();
        $result = $this->model->edit($data);
        if(!$result){
            // 回滚事务
            Db::rollback();
            $this->result([], "操作失败", 0);
        }
        $actionLog = [
            'customer_id'=>$result['id'],
            'action_log'=>json_encode($result),//创建者
            'remark'=>'edit',
            'action_admin_id'=>$this->loginInfo['id'],//操作人di
        ];
        $result = CustomerActionLogModel::create($actionLog);
        if(!$result){
            // 回滚事务
            Db::rollback();
            $this->result([], "操作失败", 0);
        }
        Db::commit();
        $this->result($result);

    }


    public function info(){
        $customerId = $this->request->param('customer_id');
        $info = $this->model->getInfo(['id'=>$customerId]);
        if($info['recommend_id']){
           // echo 3434;exit;
            $recommendInfo = RecommendModel::where('id',$info['recommend_id'])->find();
            $info['recommend_name'] = $recommendInfo['recommend_name'] ?? '';
            $info['recommend_mobile'] = $recommendInfo['recommend_mobile'] ?? '';
        }
        $this->result($info,'操作成功',1);
    }


    /**
     * 放弃客户
     * 0暂时搁置 -1放弃
     * 搁置或放弃的客户可以由总管理员重新分配负责人
     * 1正常客户 2成单客户 成单客户不允许放弃
     */
    public function discard(){
        $roles_ids = $this->role_ids;
        if(!in_array(7,$roles_ids)){
            //exception('该用户没有权限，只有业务员有操作权限！');
            $this->result([],'该用户没有权限，只有业务员有操作权限！！',0);
        }
        $data = $this->request->param();

        $rule = [
            'customer_id|客户id'=>'require',
            'customer_brand|客户选择品牌'=>'require',
            'desert_status|放弃原因'=>'require',

        ];
        //放弃原因 1价格因素 2产品满足不了客户要求 3服务不满意 4 贷款周期满足不了客户 5推荐人不满意 6其他
        $desert_status = $data['desert_status'];
        if($desert_status == 1){
            $rule['retail_price|零售价格'] = 'require';
            $rule['discount_price|优惠金额'] = 'require';
            $rule['final_price|打折后金额'] = 'require';
            $rule['budget_price|客户预算金额'] = 'require';
        }

        $this->validate($data,$rule);
        $customerId = $this->request->param('customer_id');
        //todo 验证是否有更改权限
        $status = $this->request->param('status');
        $info = $this->model->where('id',$customerId)->find();
        if(!$info){

            $this->result([],'客户不存在',0);
        }
        if($info['customer_status'] == 0 || $info['customer_status'] == '-1'){

            $this->result([],'已再审核中或已为放弃客户，请勿再操作！！',0);
        }
        //if($info['customer_status']==2) exception('客户已经成单，不允许执行操作');
        // 启动事务
        Db::startTrans();

        $result = CustomerModel::where('id',$customerId)->update(['customer_status'=>0]);//待放弃

        if($result === false){

            // 回滚事务
            Db::rollback();
            $this->result([], "操作失败", 0);
        }
        $result = CustomerDesertModel::create($data);
        if(!$result){

            // 回滚事务
            Db::rollback();
            $this->result([], "操作失败", 0);
        }
        //添加到任务里
        $nodeProcess = NodeProcessModel::where('node_id', 13)->order('id', 'asc')->find();
        $nodeInfo = NodeModel::where('id',13)->find();
        if(empty($nodeInfo)) {

            $this->result([],'任务配置已被修改',0);
        }


        $dataTask = [
            'customer_id' => $data['customer_id'],
            'order_id' => 0,
            'node_id' => 13,
            'process_id' => $nodeProcess['id'],
            'receive_admin_id' => $nodeProcess['audit_admin_id'],
            'action_table_id'=>$result['id'],//操作表id
            'admin_id'=>$this->loginInfo['id']
        ];
        $result = $this->taskModel->commonAddTask($dataTask);
        if(!$result){

            // 回滚事务
            Db::rollback();
            $this->result([], "操作失败", 0);
        }
        //$this->model->where('id',$customerId)->update(['customer_status'=>$status]);
        //todo 放弃后将删除所有关于这个客户的任务
        Db::commit();
        $this->taskModel->sendTaskInfo($dataTask['receive_admin_id'],$nodeProcess['process_name']);
        $this->result([], "操作成功", 1);
    }

    /**
     * 设置预算金额
     * setBudget
     */
    public function setBudget(){
        $customerId = $this->request->param('customer_id');
        //todo 验证是否有更改权限
        $budgetAmount = $this->request->param('budget_amount');
        $this->model->where('id',$customerId)->update(['budget_status'=>1,'budget_amount'=>$budgetAmount]);
        //todo 记录操作
        $this->result();
    }

    /**
     * 回款计划
     */
    public function saveExpect100(){
        $data = $this->request->param();
        $this->model->where('id',$data['customer_id'])->update(['expect_money_01'=>$data['expect_money_01'],'expect_money_02'=>$data['expect_money_02']]);
        $this->result();
    }
    public function saveExpect(){
        $data = $this->request->param();
        if($data['expect_payment'] > 1000){
            exception('回款计划里这个金额限制小于1000');
        }
        $this->model->where('id',$data['customer_id'])->update(['expect_status'=>$data['expect_status'],'expect_payment'=>$data['expect_payment'], 'progress_status'=> $data['progress_status']]);
        $this->result();
    }
    /**
     * 删除用户
     * @throws \Exception
     */
    public function del(){
        $id = $this->request->param('id/d');
        $this->model->del($id);
        $this->result();
    }
    //添加客户商品
    public function addCustomerGoods(){
        $roles_ids = $this->role_ids;
        if(!in_array(7,$roles_ids)){

            $this->result([],'该用户没有权限，只有业务员有操作权限！',0);
        }
        $data = $this->request->param();
        $this->validate($data,[
            'customer_id|客户id'=>'require',
            'customer_goods_names|选择产品'=>'require',
        ]);

       // $info = $this->model->where('id',$data['customer_id'])->find()->toArray();
        $customer_goods_names =CustomerGoodsDataModel::where('type',null)->where('customer_id',$data['customer_id'])->column('goods_name');

        $customer_goods_names = implode(',', $customer_goods_names);
        $goods_ids = [];
        $new_customer_goods_names = [];
        foreach ($data['customer_goods_names'] as & $v){
            $goodsInfo = GoodsModel::where('goods_name',$v)->where('pid',0)->find();
            $goods_ids[] = $goodsInfo['id'];
            $count = substr_count($customer_goods_names,  $v);

            if($count > 0){
                $count +=1;
                $new_customer_goods_names[] =  $v.$count;
            }else{
                $new_customer_goods_names[] =  $v;
            }

        }

        $customer_goods_names = implode(',',$new_customer_goods_names);
//        $update_data = $info['customer_goods_names'].','. $customer_goods_names;
//        Db::startTrans();
//        $result = $this->model->where('id',$data['customer_id'])->update(['customer_goods_names'=>$update_data]);
//        if(!$result){
//            // 回滚事务
//            Db::rollback();
//            $this->result([],'操作失败',0);
//        }
        $customer_goods_data = [];

        foreach ($new_customer_goods_names  as $k =>$v){
            $customer_goods_data[$k]['goods_id'] = $goods_ids[$k];
            $customer_goods_data[$k]['customer_id'] = $data['customer_id'];
            $customer_goods_data[$k]['goods_name'] = $v;
            $customer_goods_data[$k]['action_admin_id'] = $this->loginInfo['id'] ?? '';
        }

        $result = CustomerGoodsDataModel::insertAll($customer_goods_data);
        if(!$result){
            // 回滚事务
            Db::rollback();
            $this->result([],'操作失败',0);
        }

        Db::commit();
        $this->result([],'操作成功',1);

    }

    /**
     * 客户列表
     */
    public function index()
    {
        $pageSize      = $this->request->param('pageSize/d', 20); //每页多少条
        $pageNumber    = $this->request->param('pageNumber/d') ?? 1; //当前页
        $sortName      = $this->request->param('sortName'); //排序字段
        $sortOrder     = $this->request->param('sortOrder', 'desc'); //升序降序
        $order         = !empty($sortName) ? "{$sortName} {$sortOrder}" : ''; //排序
        $keyword = $this->request->param('keyword');
        $map = [];
        if (!empty($keyword)) {
            $map[] = ['business_name|name|mobile|address|house_estate', 'like', '%' . $keyword . '%'];
        }
        //我可以查看的客户
//        $customerIds = CustomerAuthModel::where('admin_id',$this->loginInfo['id'])->column('customer_id');
//        $map[] = ['id','in',$customerIds];
        //我创建的客户
        $myCustomerIds = CustomerAuthModel::where('admin_id',$this->loginInfo['id'])->where('role','in',['create', 'relation'])->column('customer_id');
        $taskType = $this->request->param('task_type',0);
        $customerStatus = $this->request->param('customer_status',1); //客户状态\r\n1 正常 \r\n2 成交\r\n0 待放弃 \r\n-1已放弃
        $budgetStatus = $this->request->param('budget_status',0); //预算状态 0 待预算 1已预算
        //$paymentStatus = $this->request->param('payment_status',0); //0全部 1已收款 2本月回款 3下月回款 3长期跟进
        $expect_status = $this->request->param('expect_status',0); //回款周期 本周1 本月2 下月3 长期4 待放弃5
        $designStatus = $this->request->param('design_status',0); //设计状态 0待量房 1待出图、2待审图 3待见客户 4 待确定方案

        $role_ids = $this->role_ids;
        $is_show = false;
        foreach ($role_ids as $v){
            if(in_array($v,[1,2,3,4])){
                $is_show = true;
            }
        }

        if(!$is_show){

            $map[] = ['id', 'in', $myCustomerIds];
        }

        //全部
        if ($taskType ==0) {

            switch ($customerStatus){

                case 1://正常
                    $map[] = ['customer_status','=',1];
                    break;
                case -1://放弃

                    $map[] = ['customer_status','=',-1];
                    break;
                case 0://带放弃

                    $map[] = ['customer_status','=',0];
                    break;

            }
        }

        //回款
        if ($taskType ==1) {
            $map[] =['customer_status','=',1];
            switch ($expect_status) {
                case 1:
                    $map[] = ['expect_status', '=', 1];
                    break;
                case 2:
                    $map[] = ['expect_status', '=', 2];
                    break;
                case 3:
                    $map[] = ['expect_status', '=', 3];
                    break;
                case 4:
                    $map[] = ['expect_status', '=', 4];

                    break;
                case 5:
                    $map[] = ['expect_status', '=', 5];
                    break;
            }
        }

        $data          = ['total' => 0, 'rows' => []];

        if($taskType == 2){  //设计
            $map[] =['customer_status','=',1];

            $rows = $this->model->with(['customerGoodsData' => function($query) use ($designStatus) {
                if($designStatus == 0){
                    $query->where('design_status',0)->where('type',null)->where('contract_id',null)->where('status',1);
                }elseif($designStatus == 1){
                    $query->where('design_status',1)->where('type',null)->where('contract_id',null)->where('status',1);
                }elseif($designStatus == 2){
                    $query->where('design_status',2)->where('type',null)->where('contract_id',null)->where('status',1);
                }elseif($designStatus == 3){
                    $query->where('design_status',3)->where('type',null)->where('contract_id',null)->where('status',1);
                }
            }])
                ->where($map)
               // ->page( $pageNumber,$pageSize)
                ->order($order)
                ->select();

            list($rows,$total_budget_amount) = $this->model->_formatList($rows);


        }elseif($taskType == 3){//预算
            $map[] =['customer_status','=',1];
                $rows = $this->model->with(['customerGoodsData' => function($query) use ($budgetStatus){
                    if($budgetStatus == 1){
                        $query->where('budget_status',1)->where('type',null)->where('status',1);
                    }else{

                        $query->where('budget_status',0)->where('type',null)->where('status',1);
                    }
                }])
                    ->where($map)
                    //->page($pageNumber,$pageSize)
                    ->order($order)
                    ->select();

            list($rows,$total_budget_amount)  = $this->model->_formatList($rows);


        }

        else{
            $rows = $this->model->with(['customerGoodsData'])
                ->where($map)
                ->withoutField('customer_file,customer_imgs')
                //->page($pageNumber,$pageSize)
                ->order($order)
                ->select();
            //var_dump(count($rows));exit;
                list($rows,$total_budget_amount) = $this->model->_formatList($rows);

        }
        $rows = $rows->toArray();

        array_multisort(array_column($rows, 'day_diff'), SORT_DESC, $rows);
        $data['rows'] = $rows;
        $data['total'] = count($rows) ?? 0;

        $data['total_expect_payment'] = $total_budget_amount;
        $this->result($data,'操作成功',1);
    }
    //获取登录人权限
    public function getShowRoleAuth(){
        $taskType = $this->request->param('task_type',0);
        $customer_status = $this->request->param('customer_status',1); //客户状态\r\n1 正常 \r\n2 成交\r\n0 待放弃 \r\n-1已放弃
        $budget_status = $this->request->param('budget_status',0); //预算状态 0 待预算 1已预算
        $expect_status = $this->request->param('expect_status',0); //回款周期 本周1 本月2 下月3 长期4 待放弃5
        $design_status = $this->request->param('design_status',0); //设计状态 0待量房 1待出图、2待审图 3待见客户 4 待确定方案


        $customer_id = $this->request->param('customer_id',0); //客户id
        $loginInfo = $this->loginInfo;

        $create_admin_id = CustomerAuthModel::where('customer_id',$customer_id)->where('role', 'create')->value('admin_id');
        $data = [];
        if($loginInfo['id'] != $create_admin_id){

            $role_ids = $this->role_ids;
            $customer_auth = RoleModel::where('id',$role_ids[0])->value('customer_auth');
            if($customer_auth){

                $data['customer_auth'] =  RoleAuthModel::where('type_id',1)->where('id','in',explode(',',$customer_auth) )->field('id,name')->select();
            }else{
                $data['customer_auth'] = [];
            }




            $customer_goods = RoleModel::where('id',$role_ids[0])->value('customer_goods_auth');
            $login_auth_ids =  explode(',',$customer_goods);
        }else{
            //对客户的操作权限
            $data['customer_auth'] =  RoleAuthModel::where('type_id',1)->where('id','in',[1,2,3,4,5,7,8,9,10,11] )->field('id,name')->select();
            $login_auth_ids = [18,19,20];
        }




        if($taskType == 0){
            if($customer_status == 1){

                $data['customer_goods_auth'] = RoleAuthModel::where('type_id',2)->where('id','in',$login_auth_ids )->field('id,name')->select();


            }else{
                $data['customer_auth'] =  RoleAuthModel::where('type_id',1)->where('id',21 )->field('id,name')->select();
                $data['customer_goods_auth'] = [];
            }

        }elseif($taskType == 1 ){


            $role_auth_ids = RoleAuthShowModel::where('task_type',1)->where('expect_status',$expect_status)->value('role_auth_ids');
            $data['customer_goods_auth'] = RoleAuthModel::where('type_id',2)->where('id','in',$role_auth_ids)->where('id','in',$login_auth_ids )->field('id,name')->select();


        }elseif($taskType == 2){


            $role_auth_ids = RoleAuthShowModel::where('task_type',2)->where('design_status', $design_status)->value('role_auth_ids');
            $data['customer_goods_auth'] = RoleAuthModel::where('type_id',2)->where('id','in',$role_auth_ids)->where('id','in',$login_auth_ids )->field('id,name')->select();

        }elseif($taskType == 3){


            $role_auth_ids = RoleAuthShowModel::where('task_type',3)->where('budget_status',$budget_status)->value('role_auth_ids');
            $data['customer_goods_auth'] = RoleAuthModel::where('type_id',2)->where('id','in',$role_auth_ids)->where('id','in',$login_auth_ids )->field('id,name')->select();
        }



        $this->result($data,'操作成功',1);
    }
    //todo 客户操作日志
    public function customerActionLogList(Request $request){

        $pageSize      = $this->request->param('pageSize/d', 20); //每页多少条
        $pageNumber    = $this->request->param('pageNumber/d') ?? 1; //当前页
        $customer_id    = $this->request->param('customer_id/d') ?? ''; //客户id
        $list = CustomerActionLogModel::alias('cal')
            ->leftJoin('admin a', 'a.id = cal.action_admin_id')->where('cal.customer_id',$customer_id)
            ->field('cal.id,a.nickname,cal.create_time,cal.customer_id')
             ->paginate(['list_rows'=> $pageSize, 'page' => $pageNumber]);
        $this->result($list,'操作成功',1);
    }
    //todo 获取客户操作信息
    public function getLogInfo(Request $request){
        $param = $request->param();
        //开始校验
        $this->validate($param,[
            'id|记录id'=>'require',
        ]);
        $id = $param['id'];
        $list = CustomerActionLogModel::alias('cal')
            ->leftJoin('admin a', 'a.id = cal.action_admin_id')
            ->where('cal.id',$id)
            ->field('a.nickname,cal.create_time,cal.customer_id,cal.action_log')
            ->find();
       if($list){
           $list['action_log'] = json_decode($list['action_log']);
       }
        $this->result($list,'操作成功',1);
    }
    //客户
    public function getFinishStatusByCustomerId(Request $request){
        $param = $request->param();
        //开始校验
        $this->validate($param,[
            'customer_id|客户id'=>'require',
            'property|标识' => 'require'
        ]);
        if($param['property'] == 'sk'){
            $taskInfo = TaskModel::where('customer_id',$param['customer_id'])->where('node_id',11)->where('process_id',18)->order('id','desc')->find();

            $desc = '收款';
        }elseif($param['property'] == 'tk'){
            $taskInfo = TaskModel::where('customer_id',$param['customer_id'])->where('node_id',12)->where('process_id',20)->order('id','desc')->find();

            $desc = '退款';
        }elseif($param['property'] == 'desert'){
            $taskInfo = TaskModel::where('customer_id',$param['customer_id'])->where('node_id',13)->where('process_id',22)->order('id','desc')->find();
            $desc = '放弃';
        }
        if($taskInfo && $taskInfo['audit_status'] == 0){

            $this->result([], '客户有' .$desc.'任务审核中', 0);
        }



        $this->result([],'操作成功',1);
    }
    //产品
    public function getFinishStatusByGoodsDataId(Request $request){
        $param = $request->param();
        //开始校验
        $this->validate($param,[
            'goods_data_id|商品id'=>'require',
            'property|标识' => 'require'
        ]);
        $customerGoodsDataInfo = CustomerGoodsDataModel::where('id', $param['goods_data_id'])->find();
        $where  = [];
        if($param['property'] == 'budget'){
            $actionInfo = CustomerBudgetModel::where('goods_data_id',$customerGoodsDataInfo['id'])->order('id','desc')->find();
            $where[] = ['node_name', '=', '申请预算'];


        }elseif($param['property'] == 'ruler'){
            $actionInfo = CustomerRulerModel::where('goods_data_id',$customerGoodsDataInfo['id'])->order('id','desc')->find();
            $where[] = ['node_name', '=', '申请量房'];
        }elseif($param['property'] == 'desert'){
            $actionInfo = CustomerGoodsDesertModel::where('goods_data_id',$customerGoodsDataInfo['id'])->order('id','desc')->find();
            $where[] = ['node_name', '=', '放弃品类'];
        }
        $taskInfo = TaskModel::where('action_table_id',$actionInfo['id'])->where($where)->find();


        if($taskInfo && $taskInfo['audit_status'] == 1){


            $this->result([], '商品已申请', 0);

        }elseif($taskInfo && $taskInfo['audit_status'] == 0){

            $this->result([], '商品任务审核中', 0);
        }



        $this->result([],'操作成功',1);
    }
    //显示红点数量
    public function showRedCustomerNums(){
        $myCustomerIds = CustomerAuthModel::where('admin_id',$this->loginInfo['id'])->where('role','in',['create', 'relation'])->column('customer_id');

        $role_ids = $this->role_ids;
        $is_show = false;
        foreach ($role_ids as $v){
            if(in_array($v,[1,2,3,4])){
                $is_show = true;
            }
        }
        $map = [];
        if(!$is_show){

            $map[] = ['id', 'in', $myCustomerIds];
        }
        $query = [];
        //全部-正常
        $query[1][] = ['c.customer_status','=',1];
        //全部-放弃
        $query[2][] = ['c.customer_status','=',-1];

        //回款-本周
        $query[3][] = ['c.customer_status','=',1];
        $query[3][] =  ['c.expect_status', '=', 1];
        //回款-本月
        $query[4][] = ['c.customer_status','=',1];
        $query[4][] =  ['c.expect_status', '=', 2];
        //回款-下月
        $query[5][] = ['c.customer_status','=',1];
        $query[5][] =  ['c.expect_status', '=', 3];
        //回款-长期
        $query[6][] = ['c.customer_status','=',1];
        $query[6][] =  ['c.expect_status', '=', 4];
        //回款-待放弃
        $query[7][] = ['c.customer_status','=',1];
        $query[7][] =  ['c.expect_status', '=', 5];

        //设计-待量房
        $query[8][] = ['design_status','=',0];
        //设计-待出图
        $query[9][] = ['design_status','=',1];
        //设计-待审核
        $query[10][] = ['design_status','=',2];
        //设计-待签合同
        $query[11][] = ['design_status','=',3];

        //预算-待预算
        $query[12][] = ['budget_status','=',1];
        //预算-已预算
        $query[13][] = ['budget_status','=',0];
        foreach ($query as $k=>$v){
            if($k <= 7){
                $data['total_' . $k] = $this->model->alias('c')->where($query[$k])->where($map)->count();
            }else{
                $list = $this->model->with(['customerGoodsData' => function($query1) use ($k,$query) {

                    $query1->where($query[$k])->where('type',null)->where('contract_id',null)->where('status',1);

                }])->where('customer_status',1)->where($map)->select()->toArray();

                foreach ($list as $kd=>&$v){
                    if(empty($v['customerGoodsData']) || $v['customerGoodsData'] == ''){

                        unset($list[$kd]);
                    }
                }
                $data['total_' . $k] = count($list);
            }

        }




        $this->result($data,'操作成功',1);
    }







}
